package com.exercise.AndroidCamera;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.exercise.AndroidCamera.ModifyInfoActivity.readUserInfoAsync;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
/*
기능 : 그룹정보를 볼 수 있는 기능 (서버와연동)
작성 : 하드캔
완료일 : 2014.09.26 
	*/
public class GroupInfoActivity extends BaseActivity {

	Intent mIntent;
	String groupID;
	String userID;
	
	String name="";
	String detail="";
	ArrayList<String> groupUserArray;
	
	EditText groupName;
	EditText groupExplanation;

	private ListView list;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_group_info);
		
		groupUserArray = new ArrayList<String>();
		groupID = getIntent().getExtras().getString("groupID");
		userID = getIntent().getExtras().getString("userID");
		
		groupName = (EditText)this.findViewById(R.id.groupName);
		groupExplanation = (EditText)this.findViewById(R.id.groupExplanation);
		
		list = (ListView)findViewById(R.id.my_group_user_list);
		
		readGroupInfoAsync myTask = new readGroupInfoAsync();
		myTask.execute();
		
		// ȸ�� Ż��
		findViewById(R.id.btnLeaveGroup).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
							new AlertDialog.Builder(GroupInfoActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("�׷� Ż��").setMessage("�׷� Ż���Ͻðڽ��ϱ�?")
							.setNeutralButton("No", null)
							.setPositiveButton("Yes", new DialogInterface.OnClickListener()
						   {
						     @Override
						     public void onClick( DialogInterface dialog, int which )
						     {
						       // ȸ�� Ż�� ����
						    	 leaveGroupInfoAsync myTask = new leaveGroupInfoAsync();
								 myTask.execute();
						     }
						   }).show(); 
					}
				});
		
		findViewById(R.id.btnConfirmOk).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						// TODO Auto-generated method stub
				    	Intent mIntent = new Intent(GroupInfoActivity.this, ManageGroupActivity.class);
				        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				    	mIntent.putExtra("userID", userID);
			    		startActivity(mIntent);
					}
				});


		getActionBar().setTitle("Post Memories");
		getActionBar().setDisplayShowHomeEnabled(false);
		getActionBar().setDisplayHomeAsUpEnabled(true);

	}
	
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	     
	    switch(item.getItemId()){
	    
	    case android.R.id.home:
            onBackPressed();
            break;

	    default:
	        return false;
	    }
	    return true;
	}

	protected String[] load_group_info(Context context){
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		
		try{
       	StringBuilder builder = new StringBuilder();
       	
       	URL url = new URL("http://54.199.194.197/get_group_info.php");
       	conn = (HttpURLConnection)url.openConnection();
       	
       	if(conn != null){
       		conn.setConnectTimeout(15000);	
       		conn.setReadTimeout(15000);
       		conn.setDefaultUseCaches(false);
           	conn.setDoInput(true);
           	conn.setDoOutput(true); 
           	conn.setRequestMethod("POST");
           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
              
         	StringBuffer buffer = new StringBuffer();
         	
         	buffer.append("group_id").append("=").append(groupID);
         	

            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();
            
           InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
           br = new BufferedReader(inputStream);
              
           	String line;
           	while((line = br.readLine()) != null){
           	   builder.append(line);
           	}
              
           	br.close();

           	pString =  builder.toString();
           	Log.d("pString", pString);
           	
           	JSONObject jObject = new JSONObject(pString);
           	JSONArray nameObject = new JSONArray(jObject.getString("group_name"));
           	JSONArray detailObject = new JSONArray(jObject.getString("group_detail"));
           	JSONArray userObject = new JSONArray(jObject.getString("user_id"));
           	
           	name = nameObject.getString(0);
           	Log.d("name", name);
           	detail = detailObject.getString(0);
           	
           	Log.d("userObject.length",userObject.length()+"");
           	for(int i=0; i<userObject.length(); i++){
           		groupUserArray.add(userObject.getString(i));
           	}

       	}else{
       		
       		throw new Exception("network error");
       	}
       	
       }catch(SocketTimeoutException se){
       	
       	result[1] = "network error";
       	
       }catch(Exception e){
       	
       	result[1] = e.getMessage();
       	
       }finally{
       	
       	if(conn != null)
       		conn.disconnect();

       	if(br != null){
       		try {
       			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
       	}
       }
       return result;
	}
	
	public class readGroupInfoAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(String... params) {
			load_group_info(GroupInfoActivity.this);
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
						
			groupName.setText(name);
			groupExplanation.setText(detail);

			GroupInfoAdapter adapter = new GroupInfoAdapter(GroupInfoActivity.this, R.layout.group_user_list, groupUserArray, groupUserArray.size());
			
			list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			list.setAdapter(adapter);
			
			super.onPostExecute(result);
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}
	
	protected String[] leave_group_info(Context context){
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		
		try{
       	StringBuilder builder = new StringBuilder();
       	
       	URL url = new URL("http://54.199.194.197/delete_group.php");
       	conn = (HttpURLConnection)url.openConnection();
       	
       	if(conn != null){
       		conn.setConnectTimeout(15000);	
       		conn.setReadTimeout(15000);
       		conn.setDefaultUseCaches(false); 
           	conn.setDoInput(true); 
           	conn.setDoOutput(true);  
           	conn.setRequestMethod("POST");
           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
              
         	StringBuffer buffer = new StringBuffer();
         	
         	
         	buffer.append("user_id").append("=").append(userID).append("&");
            buffer.append("group_id").append("=").append(groupID);

            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();
            
           InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
           br = new BufferedReader(inputStream);
              
           	String line;
           	while((line = br.readLine()) != null){
           	   builder.append(line);
           	}
              
           	br.close();

           	pString =  builder.toString();
           	Log.d("pString", pString);
           	
       	}else{
       		
       		throw new Exception("network error");
       	}
       	
       }catch(SocketTimeoutException se){
       	
       	result[1] = "network error";
       	
       }catch(Exception e){
       	
       	result[1] = e.getMessage();
       	
       }finally{
       	
       	if(conn != null)
       		conn.disconnect();

       	if(br != null){
       		try {
       			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
       	}
       }
       return result;
	}
	
	public class leaveGroupInfoAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(String... params) {
			leave_group_info(GroupInfoActivity.this);
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
						
			Toast.makeText(getApplicationContext(), "그룹틍 탈퇴하였습니다.", Toast.LENGTH_SHORT).show();
			mIntent = new Intent(GroupInfoActivity.this, ManageGroupActivity.class);
	        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        mIntent.putExtra("userID", userID);
    		startActivity(mIntent);
			
			super.onPostExecute(result);
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}


}
